package cn.itcast.bos.service.system.impl;

import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.mapper.PermissionMapper;
import cn.itcast.bos.pagehelper.PageResult;
import cn.itcast.bos.service.system.PermissionService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service("permissionServiceImpl")
@Transactional
public class PermissionServiceImpl implements PermissionService {

	@Autowired
	private PermissionMapper permissionMapper;
	/**
	 * ======================================================================
	 * 权限分页:
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@Override
	public PageResult findByPage(int pageNum, int pageSize) {
		PageHelper.startPage(pageNum,pageSize);
		Page<Permission> pages = (Page<Permission>) permissionMapper.findByPage();
		return new PageResult(pages.getTotal(),pages.getResult());
	}

	@Override
	public Permission selectById(Integer id) {
		return permissionMapper.selectById(id);
	}

	@Override
	public void update(Permission permission) {
		permissionMapper.update(permission);
	}

	@Override
	public void insert(Permission permission) {
		permissionMapper.insert(permission);
	}

	@Override
	public void delete(String[] ids) {
		if(ids != null && ids.length > 0){
			for (String id: ids) {
				//删除权限和角色中间表中的数据:
				//1.先查询是否有数据,如果有则删除
				List<Map<String,Object>> listMap = permissionMapper.selectRoleByPermissionId(Integer.parseInt(id));
				System.out.println(Arrays.asList(listMap));
				if(listMap != null && listMap.size() > 0){
					//删除中间表中的关联角色的数据
					permissionMapper.deleteRoleByPermissionId(Integer.parseInt(id));
				}
				//删除中间表数据之后在删除权限表中的数据:
				permissionMapper.delete(Integer.parseInt(id));
			}
		}
	}

	@Override
	public List<Permission> permission_list() {
		return permissionMapper.findByPage();
	}

	@Override
	public List<Permission> findByUser(Integer userID) {
		return permissionMapper.findByUser(userID);
	}
}